package com.mzy.linear_struct.面试150题;

import java.awt.font.NumericShaper;
import java.util.HashMap;

/**
 * @Author: mizy3
 * @Date: 2024/08/15/下午2:43
 * @Description:
 */
public class Pro167两数之和II输入有序数组 {
/*    public int[] twoSum(int[] numbers, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();


        // 3 4 9 10     t = 7
        //   i

        // m
        // k 4 v 0
        map.put(target - numbers[0], 0);
        for (int i = 1; i < numbers.length; i++) {
            if (map.containsKey(numbers[i])) {
                return new int[]{map.get(numbers[i]) + 1, i + 1};
            }
            map.put(target - numbers[i], i);
        }

        return new int[]{-1, -1};
    }*/

    public int[] twoSum(int[] numbers, int target) {
        // 双指针解法，利用数组有序性
        // 3 4 9 10     t = 7
        //   i

        int i = 0, j = numbers.length - 1;
        while (i < j) {
            int s = numbers[i] + numbers[j];
            if (s > target) {
                j--;
            } else if (s < target) {
                i++;
            } else {
                return new int[]{i + 1, j + 1};
            }
        }
        return new int[]{-1, -1};
    }
}
